/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package commands;

import SRDException.SRDException;
import SRDThread.SRDThread;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import protocol.SRDProtocol;

/**
 *
 * @author ylopez
 */
public class drepComandos {

    public static void printResoults(String flag, String[] resoults){
        System.out.println("Inicio ejecuci'on "+ flag +":");
        if (flag.equals("ldir") || flag.equals("rdir")) {
            for (int i = 0; i < resoults.length; i += 2) {
                System.out.println(resoults[i] + " " + resoults[i+1]);
            }
        }
        System.out.println("Final ejecuci'on "+ flag +".");
    }

    public static String[] ldir(String path){
        File dir = new File(path);
        File[] ficheros = dir.listFiles();
        int i = 0;
        String[] archivos = null;

        if(ficheros==null){
            System.out.println("No hay ficheros en el directorio especificado \n"+path);
        }else {
            archivos = new String[2*ficheros.length];
            while(i<ficheros.length){
                archivos[2*i] = ficheros[i].getName();
                archivos[2*i+1] = Long.toString(ficheros[i].length());
                i++;
            }
        }
        return archivos;
    }

    public static void cat(String file){
        try {
            FileReader fr;
            BufferedReader bf;
            String line = "";

            fr = new FileReader(file);
            bf = new BufferedReader(fr);
            System.out.println("Inicio ejecuci'on cat:");
            while ((line = bf.readLine())!=null) {
                System.out.print(line+"\n");
            }
            System.out.println("Final ejecuci'on cat\n");

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void connect(String[] parameter, PrintWriter out, BufferedReader in) throws SRDException{
        SRDProtocol srdpOut = new SRDProtocol("drepConnection", parameter);
        SRDProtocol srdpIn = new SRDProtocol();
        String messageFromDmon = null;
        String[] resoult;


        out.println(srdpOut.getMessage());

        while (true) {
            try {
                if ((messageFromDmon = in.readLine()) != null) {
                    break;
                }
            } catch (IOException ex) {
                Logger.getLogger(dcliComandos.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        srdpIn.setMessage(messageFromDmon);
        resoult = srdpIn.processMessage();
        if (resoult[0].equals("OK")){
            srdpOut = new SRDProtocol("replyReplyDrepConnection", null);
            out.println(srdpOut.getMessage());
        } else {
            throw new SRDException("Dmon ha rechazado la conexi'on");
        }
    }

    public static String[] saveFile(String message, String dir, Socket socket){
        String[] result = null;
        try {
            FileWriter copy = null;
            SRDProtocol p = new SRDProtocol();
            p.setMessage(message);
            result = p.processMessage();
            InputStream is = null;
            int fileSize = Integer.parseInt(result[1]);
            int bytesLeidos;
            int current = 0;
            byte[] buffer = new byte[fileSize];
            is = socket.getInputStream();
            FileOutputStream fos = new FileOutputStream(dir + "/" + result[0]); //escritura archivo
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesLeidos = is.read(buffer, 0, buffer.length); //Se lee el archivo
            current = bytesLeidos;
            do {
                bytesLeidos = is.read(buffer, current, buffer.length - current);
                if (bytesLeidos >= 0) {
                    current += bytesLeidos;
                }
            } while (fileSize > current);
            bos.write(buffer, 0, current);
            bos.flush();
            bos.close();
            result = new String[]{"OK"};
        } catch (IOException ex) {
            Logger.getLogger(drepComandos.class.getName()).log(Level.SEVERE, null, ex);
        }

        return result;

    }

    public static void disconnect(PrintWriter out, BufferedReader in, SRDThread anotherThread){
        SRDProtocol srdpOut = new SRDProtocol("drepDisconnect", null);
        out.println(srdpOut.getMessage());
//        anotherThread.interrupt();
        System.exit(1);
    }

    public static String[] existFile(SRDProtocol srdp, String directory) {
        String[] fileName = srdp.processMessage();
        String[] parameter = new String[]{"false", "0"};

        File file = new File (directory + "/" +fileName[0]);

        if (file.exists()) {
            parameter[0] = "true";
            parameter[1] = Long.toString(file.length());
        }

        return parameter;
    }

    public static void sendFile(String message, String directory, Socket socket) {
        SRDProtocol srdp = new SRDProtocol();
        srdp.setMessage(message);
        String[] result = srdp.processMessage();

        File file = new File (directory + "/" +result[0]);

        if(file.exists()){
            FileInputStream fis = null;
            try {
                byte[] buffer = new byte[(int) file.length()];
                fis = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);
                try {
                    bis.read(buffer, 0, buffer.length); // Leer
                    OutputStream os = socket.getOutputStream();
                    os.write(buffer, 0, buffer.length); //escribir en el socket
//                    os.flush();
                } catch (IOException ex) {
                    Logger.getLogger(drepComandos.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(drepComandos.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
//                try {
////                    fis.close();
//                } catch (IOException ex) {
//                    Logger.getLogger(drepComandos.class.getName()).log(Level.SEVERE, null, ex);
//                }
            }
        } else{
                System.out.println("No exite el archivo");
        }
    }

}
